﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.EntityClient;
using System.Linq;
using System.Web;

namespace RazakiBLL
{
    public static class ConnectionStringManager
    {
        private const string _MAIN_CONNECTION = "MainConnection";

        //old private const string KEY = "916B9D0A7CE845F0B88234D7B530117A";
        
        /// <summary>
        /// همیشه به آخرین مقدار داده شده به
        /// RazakiDBEntities
        /// در
        /// RazakiDAL/App.Config
        /// دقت شود تا مقدار این ثابت بروز باشد.
        /// </summary>
        private const string _EDM_CONNECTION_STRING = "metadata=res://*/RazakiModel.csdl|res://*/RazakiModel.ssdl|res://*/RazakiModel.msl;provider=System.Data.SqlClient;provider connection string=\"\"";

        /// <summary>
        /// همیشه به آخرین مقدار داده شده به
        /// RazakiDBEntities
        /// در
        /// RazakiDAL/App.Config
        /// دقت شود تا مقدار این ثابت بروز باشد.
        /// ویژگیهای اضافی
        /// provider connection string
        /// مربوط به
        /// EDM Connection
        /// در
        /// RazakiDBEntities
        /// </summary>
        private const string _EDM_CONNECTION_STRING_EXTENSION =
            ";multipleactiveresultsets=True;App=EntityFramework";

        private static string GetRaw(string name)
        {
            var rawConnectionString = ConfigurationManager.ConnectionStrings[name].ConnectionString;

            return rawConnectionString;
        }

        public static EntityConnection GetEDM()
        {
            EntityConnectionStringBuilder entityConnectionStringBuilder =
                new EntityConnectionStringBuilder(_EDM_CONNECTION_STRING);
            EntityConnection entityConnection;

            entityConnectionStringBuilder.ProviderConnectionString = string.Format("{0}{1}", Get(),
                                                                                   _EDM_CONNECTION_STRING_EXTENSION);
            entityConnection = new EntityConnection(entityConnectionStringBuilder.ToString());

            return entityConnection;
        }

        /// <summary>
        /// decrypted conneciton string.
        /// </summary>
        /// <returns></returns>
        public static string Get()
        {
            var rawConnectionString = GetRaw(_MAIN_CONNECTION);
            string decryptedConnectionString;

            decryptedConnectionString = Encryption.Decrypt(rawConnectionString, null, true);

            return decryptedConnectionString;
        }
    }
}